<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(suggest, index) in suggestions"
      :key="index"
      @click="$emit('search', suggest)"
    >
      <div v-html="highlight(suggest)" slot="title"></div
    ></van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      // handler(value) {
      //   // 监听事件的改变
      //   this.getSearchSuggestion(value)
      // },
      handler: debounce(function(val) {
        this.getSearchSuggestion(val)
      }, 1000),
      // 首次监视触发
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    async getSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('获取失败')
      }
    },
    highlight(suggest) {
      // eslint-disable-next-line no-eval
      // return text.replace(eval('/' + this.searchText + '/gi'), `<span class="active">${this.searchText}</span>`)
      const reg = new RegExp(this.searchText, 'gi')
      return suggest.replace(
        reg,
        `<span class="active">${this.searchText}</span>`
      )
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
